/*
 * Copyright 2012 Focus Technology, Co., Ltd. All rights reserved.
 */
package com.coderonrails.cdistr.master.session;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SessionServices.java
 * 
 * @author chenjianguo
 */
public class SlaveManager {
    public static SlaveManager sm = null;
    public static Map<String, SlaveInfo> cache = new HashMap<String, SlaveInfo>();
    public int maturityTime = 10000;// 失效时间

    private SlaveManager() {

    }

    public static SlaveManager getInstance() {
        if (sm == null) {
            sm = new SlaveManager();
        }
        return sm;
    }

    /**
     * 添加主机信息
     * 
     * @param info
     */
    public synchronized void addSlaveInfo(SlaveInfo info) {
        if (cache.get(info.getSlaveCode()) == null) {
            cache.put(info.getSlaveCode(), info);
        }
    }

    /**
     * 
     */
    public synchronized void refreshSlave() {
        List<String> cache_tmp = new ArrayList<String>();
        for (String key : cache.keySet()) {
            SlaveInfo slave = cache.get(key);
            if (System.currentTimeMillis() - slave.getLastChectTime() > maturityTime) {
                cache_tmp.add(key);
            }
        }

        for (String key : cache_tmp) {
            cache.remove(key);
        }
    }

    public synchronized String getSlaveInfo() {
        StringBuilder sb = new StringBuilder();
        sb.append("slaveCode\tslaveName\tstatus\tloginTime\tlastCheckTime\r\n");
        for (String key : cache.keySet()) {
            SlaveInfo slave = cache.get(key);
            sb.append(slave.toString());
            sb.append("\r\n");
        }
        return sb.toString().trim();
    }

    public synchronized void refresh(String code) {
        if (cache.get(code) != null) {
            cache.get(code).setLastChectTime(System.currentTimeMillis());
        }
    }

    public int getMaturityTime() {
        return maturityTime;
    }

    public void setMaturityTime(int maturityTime) {
        this.maturityTime = maturityTime;
    }

}
